﻿#include "shadow.h"

Shadow::Shadow(QWidget *parent)
    : QWidget(parent)
{
    startReceiver();

    isScreenRecorder=true;

    if(isScreenRecorder)
    {
        addr=QHostAddress::LocalHost;
        screen=qApp->primaryScreen();

        startScreenRecorder();
    }
}

Shadow::~Shadow()
{
    if(isScreenRecorder)
        stopScreenRecorder();

    endReceiver();
}

void Shadow::ring(const QString &title, const QString &content)
{
    Bell *bell=new Bell;
    bell->setMsg(title,content);
    bell->showMe();
}

void Shadow::startReceiver()
{
    receiver=new BaseReceiver(0,RECV_PORT);
    connect(receiver,&BaseReceiver::received,this,&Shadow::received);
    connect(&recvThread,&QThread::finished,receiver,&QObject::deleteLater);
    receiver->moveToThread(&recvThread);
    recvThread.start();
}

void Shadow::endReceiver()
{
    recvThread.quit();
    recvThread.wait();
}

void Shadow::startScreenRecorder(int msec)
{
    screenRecorderId=startTimer(msec);
}

void Shadow::stopScreenRecorder()
{
    killTimer(screenRecorderId);
}

void Shadow::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == screenRecorderId)
        captureToDatagram();
}

void Shadow::captureToDatagram()
{
    QPixmap pix=screen->grabWindow(0);
    if(pix.isNull())
        return;

    QByteArray data;
    QDataStream out(&data,QIODevice::WriteOnly);
    out << pix;

    QUdpSocket sender;
    sender.writeDatagram(data,addr,CAPTURE_PORT);

    qDebug() << "captured";
}

void Shadow::received(const QByteArray &data)
{
    QString reply=data;
    if(reply == "#shadow_exit")
    {
        qInfo() << "exit by command";
        qApp->quit();
    }

    ring("info",reply);
}
